import React, { useCallback } from 'react';
import { Image } from 'antd';
import { memo, useMemo } from 'react';
import ReactMarkdown from 'react-markdown';
import RemarkMath from 'remark-math'; // Math syntax
import RemarkBreaks from 'remark-breaks'; // Line break
import RehypeKatex from 'rehype-katex';
import RehypeRaw from 'rehype-raw';
import RemarkGfm from 'remark-gfm'; // Special markdown syntax
import CodeBlock from '@/pages/chat/components/CodeBlock';
import styles from './index.module.scss';
import RehypeExternalLinks from 'rehype-external-links';
import 'katex/dist/katex.min.css';
import { useBrowserCompatibility } from '@/hooks/event/use-browser-compatibility';

const Markdown = ({
  source = '',
  showAnimation = false,
  isDisabled = false,
  isScroll = false,
}: {
  source?: string;
  showAnimation?: boolean;
  isDisabled?: boolean;
  isScroll?: boolean;
}) => {
  const { isSupported } = useBrowserCompatibility();
  const components = useMemo<any>(
    () => ({
      img: MdImage,
      pre: RewritePre,
      code: Code,
      a: A,
    }),
    [],
  );

  const formatSource = useMemo(() => {
    const cleaned = (source || '')
      // 去除首尾空白
      .replace(/^\s+/, '')
      .replace(/\s+$/, '')
      // 去除开头多余的 <br/>、空 <p>、空 <div>
      .replace(/^(\s*<br\s*\/?>(\s|&nbsp;)*)+/i, '')
      .replace(/^(\s*<p[^>]*>(?:\s|&nbsp;|<br\s*\/?\s*>)*<\/p>\s*)+/i, '')
      .replace(/^\s*<figure[\s\S]*?<\/figure>\s*/i, '')
      // 压缩过多的连续空行
      .replace(/\n{3,}/g, '\n\n')
      // 中英文之间加空格
      .replace(
        /([\u4e00-\u9fa5\u3000-\u303f])([a-zA-Z0-9])|([a-zA-Z0-9])([\u4e00-\u9fa5\u3000-\u303f])/g,
        '$1$3 $2$4',
      )
      .replace(/\n*(\[QUOTE SIGN\]\(.*\))/g, '$1');

    return cleaned;
  }, [source]);

  const urlTransform = useCallback((val: string) => {
    return val;
  }, []);

  try {
    return (
      <div className="relative">
        <ReactMarkdown
          className={`markdown ${styles.markdown}
        ${showAnimation ? `${formatSource ? styles.waitingAnimation : styles.animation}` : ''}
        ${isScroll ? 'hide-scrollbar h-[100px] overflow-y-auto' : ''}
      `}
          remarkPlugins={
            [RemarkMath, [RemarkGfm, { singleTilde: false }], RemarkBreaks]
            // isSupported
            //   ? [RemarkMath, [RemarkGfm, { singleTilde: false }], RemarkBreaks]
            //   : [RemarkMath, RemarkBreaks]
          }
          // remarkPlugins={[RemarkMath, [RemarkGfm, { singleTilde: false }], RemarkBreaks]}
          rehypePlugins={
            [RehypeKatex, RehypeRaw, [RehypeExternalLinks, { target: '_blank' }]] as any[]
          }
          components={components}
          urlTransform={urlTransform}
        >
          {formatSource}
        </ReactMarkdown>
        {isDisabled && <div className="absolute bottom-0 left-0 right-0 top-0" />}
      </div>
    );
  } catch (error) {
    console.log('error : ', error);
    return (
      <div className="relative">
        {formatSource}
        {isDisabled && <div className="absolute bottom-0 left-0 right-0 top-0" />}
      </div>
    );
  }
};

export default memo(Markdown);

function RewritePre({ children }: any) {
  const modifiedChildren = React.Children.map(children, (child) => {
    if (React.isValidElement(child)) {
      // @ts-ignore
      return React.cloneElement(child, { codeBlock: true });
    }
    return child;
  });

  return <>{modifiedChildren}</>;
}

function MdImage({ src }: { src?: string }) {
  return (
    <div className="text-center">
      <Image src={src} style={{ maxHeight: '200px' }} preview={false} />
    </div>
  );
}

/* Custom dom */
function Code(e: any) {
  const { className, codeBlock, children, inline, ...props } = e;
  const match = /language-(\w+)/.exec(className || '');
  const codeType = match?.[1];

  const strChildren = String(children);

  const Component = useMemo(() => {
    const match = /language-(\w+)/.exec(className || '');
    return !inline && match ? (
      <CodeBlock language={match[1]} code={String(children).replace(/\n$/, '')} />
    ) : (
      <code className={className} {...props}>
        {children}
      </code>
    );
    // return <div>{children}</div>;
  }, [codeType, className, codeBlock, match, children, strChildren]);

  return Component;
}

function A({ children, ...props }: any) {
  const href = props.href || '';
  const linkText = (props?.children && props?.children.length > 0 && props?.children[0]) || '';

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    if (!href || href === '#' || href === '') {
      e.preventDefault(); // 阻止默认跳转行为
      e.stopPropagation(); // 阻止事件冒泡
      // handleSend(linkText as string); // 调用传入的 handleSend 函数
    } else {
      e.preventDefault();
      window.open(href, '_blank');
    }
  };

  return (
    <a {...props} href="#" onClick={handleClick} style={{ cursor: 'pointer', color: '#1890ff' }}>
      {props.children || children}
    </a>
  );
}
